package goods

import (
	"context"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"mxshop_api/goods-web/api"
	"mxshop_api/goods-web/forms"
	"mxshop_api/goods-web/global"
	"mxshop_api/goods-web/proto"
)

func List(ctx *gin.Context) {
	request := &proto.GoodsFilterRequest{}
	// 商品的列表
	priceMin := ctx.DefaultQuery("pmin", "0")
	priceMinInt, _ := strconv.Atoi(priceMin)
	request.PriceMin = int32(priceMinInt)

	priceMax := ctx.DefaultQuery("pmax", "0")
	priceMaxInt, _ := strconv.Atoi(priceMax)
	request.PriceMax = int32(priceMaxInt)

	isHot := ctx.DefaultQuery("ih", "false")
	if isHot == "1" {
		request.IsHot = true
	}
	isNew := ctx.DefaultQuery("in", "false")
	if isNew == "1" {
		request.IsNew = true
	}
	isTab := ctx.DefaultQuery("it", "0")
	if isTab == "1" {
		request.IsTab = true
	}

	category := ctx.DefaultQuery("ct", "0")
	categoryInt, _ := strconv.Atoi(category)
	request.TopCategory = int32(categoryInt)

	pages := ctx.DefaultQuery("p", "0")
	pagesInt, _ := strconv.Atoi(pages)
	request.Pages = int32(pagesInt)
	pagePerNums := ctx.DefaultQuery("pnum", "0")
	pagePerNumsInt, _ := strconv.Atoi(pagePerNums)
	request.PagePerNums = int32(pagePerNumsInt)

	keyWords := ctx.DefaultQuery("q", "")
	request.KeyWords = keyWords

	brand := ctx.DefaultQuery("b", "0")
	brandInt, _ := strconv.Atoi(brand)
	request.Brand = int32(brandInt)

	// 调用grpc服务
	r, err := global.GoodsSrvClient.GoodsList(context.Background(), request)
	if err != nil {
		zap.S().Errorw("[List] 查询商品列表失败")
		api.HandleGrpcError2Http(ctx, err)
		return
	}
	reMap := map[string]interface{}{
		"total": r.Total,
	}
	goodsList := make([]interface{}, 0)
	for _, v := range r.Data {
		goodsList = append(goodsList, map[string]interface{}{
			"id":          v.Id,
			"name":        v.Name,
			"goods_brief": v.GoodsBrief,
			"desc":        v.GoodsDesc,
			"ship_free":   v.ShipFree,
			"images":      v.Images,
			"desc_images": v.DescImages,
			"front_image": v.GoodFrontImage,
			"shop_price":  v.ShopPrice,
			"category": map[string]interface{}{
				"id":   v.Category.Id,
				"name": v.Category.Name,
			},
			"brand": map[string]interface{}{
				"id":   v.Brand.Id,
				"name": v.Brand.Name,
				"logo": v.Brand.Logo,
			},
			"is_hot":  v.IsHot,
			"is_new":  v.IsNew,
			"on_sale": v.OnSale,
		})
	}
	reMap["data"] = goodsList
	ctx.JSON(http.StatusOK, reMap)
}

func New(ctx *gin.Context) {
	// 新建商品
	goodsForm := forms.GoodsForm{}
	if err := ctx.ShouldBind(&goodsForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	goodsClient := global.GoodsSrvClient
	rsp, err := goodsClient.CreateGoods(context.Background(), &proto.CreateGoodsInfo{
		Name:           goodsForm.Name,
		GoodsSn:        goodsForm.GoodsSn,
		Stocks:         goodsForm.Stocks,
		MarketPrice:    goodsForm.MarketPrice,
		ShopPrice:      goodsForm.ShopPrice,
		GoodsBrief:     goodsForm.GoodsBrief,
		ShipFree:       *goodsForm.ShipFree,
		Images:         goodsForm.Images,
		DescImages:     goodsForm.DescImages,
		GoodFrontImage: goodsForm.FrontImage,
		CategoryId:     goodsForm.CategoryId,
		BrandId:        goodsForm.Brand,
	})
	if err != nil {
		api.HandleGrpcError2Http(ctx, err)
		return
	}
	// TODO - 商品的库存
	ctx.JSON(http.StatusOK, rsp)
}

func Detail(ctx *gin.Context) {
	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}
	r, err := global.GoodsSrvClient.GetGoodsDetail(context.Background(), &proto.GoodInfoRequest{
		Id: int32(i),
	})
	if err != nil {
		api.HandleGrpcError2Http(ctx, err)
		return
	}
	// 去库存服务查询库存
	// TODO - 商品的库存

	rsp := map[string]interface{}{
		"id":          r.Id,
		"name":        r.Name,
		"goods_brief": r.GoodsBrief,
		"desc":        r.GoodsDesc,
		"ship_free":   r.ShipFree,
		"images":      r.Images,
		"desc_images": r.DescImages,
		"front_image": r.GoodFrontImage,
		"shop_price":  r.ShopPrice,
		"category": map[string]interface{}{
			"id":   r.Category.Id,
			"name": r.Category.Name,
		},
		"brand": map[string]interface{}{
			"id":   r.Brand.Id,
			"name": r.Brand.Name,
			"logo": r.Brand.Logo,
		},
		"is_hot":  r.IsHot,
		"is_new":  r.IsNew,
		"on_sale": r.OnSale,
	}

	ctx.JSON(http.StatusOK, rsp)
}

func Delete(ctx *gin.Context) {
	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}
	_, err = global.GoodsSrvClient.DeleteGoods(context.Background(), &proto.DeleteGoodsInfo{
		Id: int32(i),
	})
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	//ctx.Status(http.StatusOK)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
	return
}

// 获取商品的库存
func Stocks(ctx *gin.Context) {
	id := ctx.Param("id")
	_, err := strconv.ParseInt(id, 10, 32)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}
	// TODO - 商品的库存
	return
}

// 更新商品状态信息
func UpdateStatus(ctx *gin.Context) {
	goodsClient := global.GoodsSrvClient

	goodsStatusForm := forms.GoodsStatusForm{}
	if err := ctx.ShouldBindJSON(&goodsStatusForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	_, err = goodsClient.UpdateGoods(context.Background(), &proto.CreateGoodsInfo{
		Id:     int32(i),
		IsHot:  *goodsStatusForm.IsHot,
		IsNew:  *goodsStatusForm.IsNew,
		OnSale: *goodsStatusForm.OnSale,
	})
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}

// 更新商品全量信息
func Update(ctx *gin.Context) {
	goodsClient := global.GoodsSrvClient

	goodsForm := forms.GoodsForm{}
	if err := ctx.ShouldBindJSON(&goodsForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	id := ctx.Param("id")
	i, err := strconv.ParseInt(id, 10, 32)
	_, err = goodsClient.UpdateGoods(context.Background(), &proto.CreateGoodsInfo{
		Id:             int32(i),
		Name:           goodsForm.Name,
		GoodsSn:        goodsForm.GoodsSn,
		Stocks:         goodsForm.Stocks,
		MarketPrice:    goodsForm.MarketPrice,
		ShopPrice:      goodsForm.ShopPrice,
		GoodsBrief:     goodsForm.GoodsBrief,
		ShipFree:       *goodsForm.ShipFree,
		Images:         goodsForm.Images,
		DescImages:     goodsForm.DescImages,
		GoodFrontImage: goodsForm.FrontImage,
		CategoryId:     goodsForm.CategoryId,
		BrandId:        goodsForm.Brand,
	})
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "更新成功",
	})
}
